package iamdev.me.ytds.interceptor;

import com.alibaba.fastjson.JSON;
import iamdev.me.ytds.annotation.Login;
import iamdev.me.ytds.entity.User;
import iamdev.me.ytds.json.ActionMessage;
import iamdev.me.ytds.service.IUserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * Title: LoginInterceptor.java

 * @author zxc
 * @time 2018/3/22 16:32
 */


public class LoginInterceptor implements HandlerInterceptor {
    private Logger logger= LoggerFactory.getLogger(this.getClass());

    private IUserService userService;

    public LoginInterceptor(IUserService userService){
        this.userService=userService;
    }


    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object handler) throws Exception {
        if(handler instanceof HandlerMethod){
            Login login=((HandlerMethod) handler).getMethodAnnotation(Login.class);
            if(login!=null){
                logger.info("login拦截,{}",httpServletRequest.getRequestURL().toString());
                HttpSession httpSession = httpServletRequest.getSession(true);
                User user =(User) httpSession.getAttribute("user");
                if(user==null){
                    Cookie cookies [] = httpServletRequest.getCookies();
                    for(Cookie cookie:cookies){
                        if(cookie.getName().equals("token")){
                            user = userService.findUserByToken(cookie.getValue());
                            if(user!=null){
                                httpSession.setAttribute("user",user);
                                return true;
                            }
                        }
                    }
                    ActionMessage am=ActionMessage.fail();
                    am.setCode(ActionMessage.unLogin);
                    am.setMessage("未登录");
                    httpServletResponse.setContentType("application/json;charset=UTF-8");
                    httpServletResponse.getWriter().print(JSON.toJSONString(am));
                    return false;
                }
            }
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }
}
